print("熊猫人之谜猎人技能提示工具")

---------------------- [1] 常量定义 ----------------------
-- 预定义纹理ID（熊猫人之谜版本）
local TEXTURE_EAGLE = 136076   -- 雄鹰守护
local TEXTURE_SERPENT = 132204 -- 毒蛇钉刺
local TEXTURE_bzsj = 236178 -- 爆炸射击
local TEXTURE_KILL_SHOT = 236174 -- 爆炸射击
local TEXTURE_IMMOLATE = 135817 -- 献祭的法术图标ID

-- 法术ID
local SPELL_SERPENT_STING = 1978    -- 毒蛇钉刺施放ID
local SPELL_ARCANE_SHOT_ID = 3044
local SPELL_STEADY_SHOT_ID = 56641
local DEBUFF_SERPENT_STING = 118253 -- 毒蛇钉刺debuff ID
local BUFF_EAGLE = 13165            -- 雄鹰守护buff ID
local EXPLOSIVE_SHOT_SPELL_ID = 53301 -- 爆炸射击法术ID
local DEBUFF_IMMOLATE = 47811 -- 献祭的debuff ID

-- 系统常量
local MAX_AURA_SCANS = 40  -- 最大光环扫描次数
local GCD_DURATION = 1.5   -- 公共冷却时间
local EXPLOSIVE_FOCUS_COST = 25  -- 爆炸射击集中值消耗
local ARCANE_FOCUS_COST = 50     -- 奥术射击集中值消耗
local SPELL_POWER_FOCUS = 2      -- 集中值类型ID
local STEADY_SHOT_FOCUS_GAIN = 14  -- 稳固射击获得的集中值
local EXPLOSIVE_COOLDOWN_THRESHOLD = 3  -- 爆炸射击冷却完成阈值（秒）

local ADDON_NAME = "haha-ss-wlk-new"
HunterSkillReminderPosition = HunterSkillReminderPosition or {}

---------------------- [2] 主技能提示框架 ----------------------
local skillTipFrame = CreateFrame("Frame", nil, UIParent)
skillTipFrame:SetSize(124, 40)
skillTipFrame:SetPoint("CENTER", UIParent, "CENTER", 0, -130)

-- 创建图标函数
local function CreateSkillIcon(parent, texture, size, point, relativeTo, relativePoint, x, y)
    local icon = parent:CreateTexture(nil, "OVERLAY")
    icon:SetSize(size, size)
    icon:SetPoint(point, relativeTo, relativePoint, x, y)
    icon:SetTexture(texture)
    return icon
end

-- 创建雄鹰守护图标
local eagleIcon = CreateSkillIcon(skillTipFrame, TEXTURE_EAGLE, 40, "LEFT", skillTipFrame, "LEFT", 0, 0)
eagleIcon:Hide()

-- 创建爆炸射击图标
local immolateIcon = skillTipFrame:CreateTexture(nil, "OVERLAY")
immolateIcon:SetSize(40, 40)
immolateIcon:SetPoint("LEFT", eagleIcon, "RIGHT", 0, 0)
immolateIcon:SetTexture(TEXTURE_IMMOLATE)
immolateIcon:Hide()

-- 创建爆炸射击图标
local bzsjIcon1 = skillTipFrame:CreateTexture(nil, "OVERLAY")
bzsjIcon1:SetSize(40, 40)
bzsjIcon1:SetPoint("LEFT", eagleIcon, "RIGHT", 0, 0)
bzsjIcon1:SetTexture(TEXTURE_bzsj)
bzsjIcon1:Hide()

-- 创建奥术射击图标
local arcaneIcon = skillTipFrame:CreateTexture(nil, "OVERLAY")
arcaneIcon:SetSize(40, 40)
arcaneIcon:SetPoint("LEFT", eagleIcon, "RIGHT", 0, 0)
arcaneIcon:SetTexture(132218)
arcaneIcon:Hide()

-- 创建稳固射击图标
local wgsjIcon1 = skillTipFrame:CreateTexture(nil, "OVERLAY")
wgsjIcon1:SetSize(40, 40)
wgsjIcon1:SetPoint("LEFT", eagleIcon, "RIGHT", 0, 0)
wgsjIcon1:SetTexture(132213)
wgsjIcon1:Hide()

-- 创建杀戮射击图标
local killShotIcon = skillTipFrame:CreateTexture(nil, "OVERLAY")
killShotIcon:SetSize(40, 40)
killShotIcon:SetPoint("LEFT", eagleIcon, "RIGHT", 0, 0)
killShotIcon:SetTexture(TEXTURE_KILL_SHOT)
killShotIcon:Hide()

-- 创建两个毒蛇钉刺图标
local serpentIcon1 = skillTipFrame:CreateTexture(nil, "OVERLAY")
serpentIcon1:SetSize(40, 40)
serpentIcon1:SetPoint("LEFT", eagleIcon, "RIGHT", 0, 0)
serpentIcon1:SetTexture(TEXTURE_SERPENT)
serpentIcon1:Show()

local serpentIcon2 = skillTipFrame:CreateTexture(nil, "OVERLAY")
serpentIcon2:SetSize(40, 40)
serpentIcon2:SetPoint("LEFT", serpentIcon1, "RIGHT", 0, 0)
serpentIcon2:SetTexture(TEXTURE_SERPENT)
serpentIcon2:Hide()

local dcsjIcon = skillTipFrame:CreateTexture(nil, "OVERLAY")
dcsjIcon:SetSize(40, 40)
dcsjIcon:SetPoint("LEFT", serpentIcon1, "RIGHT", 0, 0)
dcsjIcon:SetTexture(132330)
dcsjIcon:Hide()

local wgsjIcon2 = skillTipFrame:CreateTexture(nil, "OVERLAY")
wgsjIcon2:SetSize(40, 40)
wgsjIcon2:SetPoint("LEFT", serpentIcon1, "RIGHT", 0, 0)
wgsjIcon2:SetTexture(132213)
wgsjIcon2:Hide()

-- AOE时的爆炸射击
local bzsjIcon2 = skillTipFrame:CreateTexture(nil, "OVERLAY")
bzsjIcon2:SetSize(40, 40)
bzsjIcon2:SetPoint("LEFT", serpentIcon1, "RIGHT", 0, 0)
bzsjIcon2:SetTexture(TEXTURE_bzsj)
bzsjIcon2:Show()

---------------------- [3] 控制面板创建 ----------------------
-- 创建控制面板（200x400）
local controlPanel = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
controlPanel:SetSize(200, 200)
controlPanel:SetPoint("RIGHT", UIParent, "RIGHT", -20, 0)

-- 设置面板背景和边框
controlPanel:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
    edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
    tile = true,
    tileSize = 32,
    edgeSize = 32,
    insets = { left = 11, right = 11, top = 11, bottom = 9 }
})
controlPanel:SetBackdropColor(0, 0, 0, 0.8)
controlPanel:SetBackdropBorderColor(0.5, 0.5, 0.5, 1)

-- 面板标题
local titleText = controlPanel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
titleText:SetPoint("TOP", controlPanel, "TOP", 0, -15)
titleText:SetText("猎人技能管理")
titleText:SetTextColor(1, 0.8, 0) -- 金色标题

---------------------- [4] 位置管理 ----------------------

---- 保存位置函数
local function SavePosition()
    print("调用保存方法")
    local point, relativeTo, relativePoint, x, y = skillTipFrame:GetPoint()
    print("point==" .. point)
    if relativeTo then
        print("relativeTo==" .. relativeTo)
    end
    print("relativePoint==" .. relativePoint)
    HunterSkillReminderPosition = {
        x = x,
        y = y,
        point = point,
        relativePoint = relativePoint
    }
end

-- 加载位置函数
local function LoadPosition()
    if HunterSkillReminderPosition then
        skillTipFrame:ClearAllPoints()
        skillTipFrame:SetPoint(
                HunterSkillReminderPosition.point,
                UIParent,
                HunterSkillReminderPosition.relativePoint,
                HunterSkillReminderPosition.x,
                HunterSkillReminderPosition.y
        )
        return true
    end
    return false
end

-- 位置初始化函数
local function InitializePosition()
    -- 创建事件处理框架
    local loaderFrame = CreateFrame("Frame")
    loaderFrame:RegisterEvent("ADDON_LOADED")

    loaderFrame:SetScript("OnEvent", function(self, event, addonName)
        if event == "ADDON_LOADED" and addonName == ADDON_NAME then
            print("插件加载完成:", addonName)
            if not LoadPosition() then
                print("没有保存的位置，使用默认位置")
                skillTipFrame:SetPoint("CENTER", UIParent, "CENTER", 0, -130)
            end
            self:UnregisterEvent("ADDON_LOADED")
        end
    end)
end

-- 添加拖动功能
controlPanel:SetMovable(true)
controlPanel:EnableMouse(true)
controlPanel:SetClampedToScreen(true) -- 防止拖出屏幕
controlPanel:RegisterForDrag("LeftButton") -- 左键拖动

-- 设置拖动脚本
controlPanel:SetScript("OnDragStart", controlPanel.StartMoving)
controlPanel:SetScript("OnDragStop", controlPanel.StopMovingOrSizing)

---------------------- [3] 重置位置功能 ----------------------



-- 位置重置函数
local function ResetPosition()
    skillTipFrame:ClearAllPoints()
    skillTipFrame:SetPoint("CENTER", UIParent, "CENTER", 0, -130)
    print("技能图标位置已重置！")
    SavePosition()  -- 保存位置
end

-- 在控制面板中添加重置按钮
local resetButton = CreateFrame("Button", nil, controlPanel, "UIPanelButtonTemplate")
resetButton:SetSize(120, 25)
resetButton:SetPoint("TOP", titleText, "BOTTOM", 0, -20)
resetButton:SetText("重置图标位置")
resetButton:SetScript("OnClick", ResetPosition)

-- 添加重置按钮提示
local resetTip = controlPanel:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
resetTip:SetPoint("TOP", resetButton, "BOTTOM", 0, -5)
resetTip:SetText("将技能图标恢复默认位置")
resetTip:SetTextColor(0.8, 0.8, 0.8)

---------------------- [4] 位置锁定功能 ----------------------
-- 创建锁定复选框
local lockCheck = CreateFrame("CheckButton", nil, controlPanel, "UICheckButtonTemplate")
lockCheck:SetSize(24, 24)
lockCheck:SetPoint("TOP", resetTip, "BOTTOM", 0, -20)

-- 设置复选框文本
lockCheck.text = lockCheck:CreateFontString(nil, "OVERLAY", "GameFontNormal")
lockCheck.text:SetPoint("LEFT", lockCheck, "RIGHT", 5, 0)
lockCheck.text:SetText("锁定位置")
lockCheck.text:SetTextColor(1, 1, 1)

-- 初始状态为锁定
lockCheck:SetChecked(true)

-- 锁定/解锁功能实现
local function UpdateLockState()
    local locked = lockCheck:GetChecked()
    skillTipFrame:EnableMouse(not locked) -- 锁定后禁用鼠标交互
    skillTipFrame:SetMovable(not locked)  -- 锁定后禁止移动
    print(locked and "图标已锁定" or "图标已解锁")
end

-- 初始设置锁定状态
UpdateLockState()

-- 绑定点击事件
lockCheck:SetScript("OnClick", UpdateLockState)

---------------------- [5] 拖动功能 ----------------------
-- 拖动支持（受锁定状态控制）
skillTipFrame:SetMovable(true)
skillTipFrame:RegisterForDrag("LeftButton")

-- 设置拖动脚本
skillTipFrame:SetScript("OnDragStart", function(self)
    if self:IsMovable() then
        -- 检查是否解锁
        self:StartMoving()
    end
end)

-- 修改拖动停止函数，添加位置保存
skillTipFrame:SetScript("OnDragStop", function(self)
    if self:IsMovable() then
        self:StopMovingOrSizing()
        print("2222222222222222")
        SavePosition()  -- 保存位置
        print("1111111111111111")
    end
end)

-- 在文件顶部添加光环检测辅助函数
local function FindBuff(spellId)
    for i = 1, MAX_AURA_SCANS do
        local _, _, _, _, _, _, _, _, _, buffSpellId = UnitBuff("player", i, "PLAYER")
        if not buffSpellId then
            break
        end
        if buffSpellId == spellId then
            return true
        end
    end
    return false
end

local function FindDebuff(spellId)
    for i = 1, MAX_AURA_SCANS do
        local _, _, _, _, _, expiration, _, _, _, debuffSpellId = UnitDebuff("target", i, "PLAYER")
        if not debuffSpellId then
            break
        end
        if debuffSpellId == spellId then
            return expiration > GetTime()  -- 返回是否有效
        end
    end
    return false
end

---------------------- 毒蛇钉刺的检测 ----------------------
local lockSerpentStingCheck = false;
local serpentCastTime = 0  -- 记录施放时间

skillTipFrame:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED")
skillTipFrame:RegisterEvent("UNIT_SPELLCAST_STOP")
skillTipFrame:RegisterEvent("PLAYER_TARGET_CHANGED")
skillTipFrame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")  -- 添加战斗日志事件
skillTipFrame:SetScript("OnEvent", function(self, event, ...)
    if event == "UNIT_SPELLCAST_SUCCEEDED" then
        local unit, _, spellID = ...
        if unit == "player" and spellID == SPELL_SERPENT_STING then
            lockSerpentStingCheck = true;
        end
    elseif event == "UNIT_SPELLCAST_STOP" and unit == "player" and spellID == SPELL_SERPENT_STING then
        local unit, _, spellID = ...
        if unit == "player" and spellID == SPELL_SERPENT_STING then
            lockSerpentStingCheck = false;
        end
    elseif event == "PLAYER_TARGET_CHANGED" then
        lockSerpentStingCheck = false
    elseif event == "COMBAT_LOG_EVENT_UNFILTERED" then
        local _, subEvent, _, sourceGUID, sourceName, _, _, destGUID, destName, _, _, spellId = CombatLogGetCurrentEventInfo()

        -- 检查是否是玩家施放的毒蛇钉刺未命中
        if sourceGUID == UnitGUID("player") and spellId == SPELL_SERPENT_STING then
            if subEvent == "SPELL_MISSED" or subEvent == "SPELL_DODGED" or subEvent == "SPELL_PARRYED" then
                -- 毒蛇钉刺未命中、被躲闪或被招架，重置锁定状态
                lockSerpentStingCheck = false
            end
        end
    end
end)

-- 在OnUpdate函数中修改奥术射击检测部分
local function CalculateArcaneFocusRequirement()
    -- 获取当前集中值
    local currentFocus = UnitPower("player", Enum.PowerType.Focus)

    -- 检查是否正在施放稳固射击
    local castingSteadyShot = false
    local _, _, _, _, startTime, endTime, _, _, castingSpellID = UnitCastingInfo("player")
    if not castingSpellID then
        _, _, _, _, startTime, endTime, _, castingSpellID = UnitChannelInfo("player")
    end

    if castingSpellID == SPELL_STEADY_SHOT_ID then
        castingSteadyShot = true
    end

    -- 预测集中值
    local predictedFocus = currentFocus
    if castingSteadyShot then
        -- 如果正在施放稳固射击，增加预测值
        predictedFocus = predictedFocus + STEADY_SHOT_FOCUS_GAIN
    end

    -- 返回预测值
    return predictedFocus
end

-- 设置更新频率
local updateInterval = 0.2
local elapsed = 0

skillTipFrame:SetScript("OnUpdate", function(self, delta)

    -- 献祭的判断
    local hasImmolateDebuff = FindDebuff(DEBUFF_IMMOLATE)
    if hasImmolateDebuff then
        immolateIcon:Hide()
    else
        immolateIcon:Show()
    end

    elapsed = elapsed + delta
    if elapsed < updateInterval then
        return
    end
    elapsed = 0

    -- 战斗状态变化时可添加视觉反馈
    local inCombat = UnitAffectingCombat("player")
    if inCombat then
        -- 战斗中的处理逻辑
        local leanEagle = IsSpellKnown(BUFF_EAGLE)
        if leanEagle then
            local hasEagleBuff = FindBuff(BUFF_EAGLE)
            if hasEagleBuff then
                eagleIcon:Hide()
            else
                eagleIcon:Show()
            end
        end
    else
        -- 非战斗状态处理
        eagleIcon:Hide()
    end

    -- 获取当前集中值
    local currentFocus = UnitPower("player", Enum.PowerType.Focus)

    ---------------毒蛇钉刺检测
    -- 是否需要释放毒蛇钉刺的变量
    local leanSerpentSting = IsSpellKnown(SPELL_SERPENT_STING)
    local needSpellSerpent = false
    if leanSerpentSting then
        local hasSerpentDebuff = FindDebuff(DEBUFF_SERPENT_STING)
        if hasSerpentDebuff then
            lockSerpentStingCheck = false
        end
        needSpellSerpent = not hasSerpentDebuff and not lockSerpentStingCheck
    end

    if lockSerpentStingCheck then
        serpentIcon1:Hide()
    else
        if needSpellSerpent and leanSerpentSting and currentFocus >= 15 then
            serpentIcon1:Show()
        else
            serpentIcon1:Hide()
        end
    end
    ---------------毒蛇钉刺检测

    -- 爆炸射击冷却状态检测
    local leanExplosiveShot = IsSpellKnown(EXPLOSIVE_SHOT_SPELL_ID)
    local explosiveAvailable = false
    local explosiveCooldownRemaining = 0  -- 爆炸射击剩余冷却时间
    if leanExplosiveShot then
        local start, duration, enabled = GetSpellCooldown(EXPLOSIVE_SHOT_SPELL_ID)
        if enabled ~= 0 then
            -- 技能可用
            -- 技能可用且不在冷却中（包括GCD期间也视为可用）
            if duration == 0 or duration <= 1.5 then
                explosiveAvailable = true
            else
                explosiveCooldownRemaining = start + duration - GetTime()
            end
        end

        if currentFocus < EXPLOSIVE_FOCUS_COST then
            explosiveAvailable = false
        end

    end

    -- 显示条件
    local showExplosive = explosiveAvailable and (not needSpellSerpent or lockSerpentStingCheck)
    bzsjIcon1:SetShown(showExplosive)

    -- 判断是否打杀戮射击
    local targetHealth = UnitHealth("target");
    local targetHealthMax = UnitHealthMax("target");
    local healthRate = targetHealth / targetHealthMax;
    local showKillShot = false;
    if healthRate < 0.2 then
        local usable, nomana = IsUsableSpell("杀戮射击");
        if usable then
            showKillShot = true
            killShotIcon:Show();
        end
    else
        showKillShot = false
        killShotIcon:Hide();
    end

    -- 奥术射击可用性检测
    local arcaneAvailable = false
    if IsSpellKnown(SPELL_ARCANE_SHOT_ID) then
        local predictedFocus = CalculateArcaneFocusRequirement()
        if explosiveCooldownRemaining > 0 and explosiveCooldownRemaining < 3 then
            arcaneAvailable = predictedFocus >= 60
        else
            arcaneAvailable = predictedFocus >= ARCANE_FOCUS_COST
        end

    end
    local showArcane = not explosiveAvailable and not needSpellSerpent and arcaneAvailable and not showKillShot
    arcaneIcon:SetShown(showArcane)

    -- 修改稳固射击检测
    local showSteady = not explosiveAvailable and not needSpellSerpent and not arcaneAvailable and not showKillShot
    wgsjIcon1:SetShown(showSteady and IsSpellKnown(SPELL_STEADY_SHOT_ID))

    -- AOE时的的显示策略
    if currentFocus > 25 then
        if explosiveAvailable then
            bzsjIcon2:Show()
            dcsjIcon:Hide()
            wgsjIcon2:Hide()
        else
            if currentFocus > 50 then
                bzsjIcon2:Hide()
                dcsjIcon:Show()
                wgsjIcon2:Hide()
            else
                bzsjIcon2:Hide()
                dcsjIcon:Hide()
                wgsjIcon2:Show()
            end
        end
    else
        bzsjIcon2:Hide()
        dcsjIcon:Hide()
        wgsjIcon2:Show()
    end


end)

---------------------- [7] 添加斜杠命令 ----------------------
-- 注册重置位置斜杠命令
SLASH_RESETPOSITION1 = "/rp" -- 主命令
SLASH_RESETPOSITION2 = "/resetpos" -- 备用命令
SlashCmdList["RESETPOSITION"] = ResetPosition

-- 注册锁定/解锁斜杠命令
SLASH_LOCKUI1 = "/lockui"
SlashCmdList["LOCKUI"] = function()
    lockCheck:SetChecked(not lockCheck:GetChecked())
    UpdateLockState()
end

-- 添加提示信息
print("控制命令:")
print("- /rp 或 /resetpos: 重置图标位置")
print("- /lockui: 切换锁定状态")
print("- 控制面板位于屏幕右侧")

---------------------- [13] 位置初始化 ----------------------
InitializePosition()
